/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.test;

import com.alibaba.fastjson.JSON;
import com.jili.ubert.code.client2server.BasketCancelOrders;
import com.jili.ubert.code.client2server.BasketOrders;
import com.jili.ubert.code.client2server.CancelOrder;
import com.jili.ubert.code.client2server.NewOrder;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.avis.client.Elvin;
import org.avis.client.Notification;
import org.avis.client.NotificationListener;
import org.avis.client.Subscription;

/**
 *
 * @author ChengJili
 */
public class SimSendOrder {

    private static final Log log = LogFactory.getLog(SimSendOrder.class);
    private static Elvin elvin = null;
    private static int id = 1;

    static {
        String elvinUri = System.getProperty("elvin", "elvin://localhost");
        try {
            elvin = new Elvin(elvinUri);
            log.info("启动连接avis router:" + elvinUri);
            //System.out.println("启动连接avis router:"+elvinUri);
            elvin.closeOnExit();
            final Subscription orderSubscription = elvin.subscribe("Title == 'Report' && PipID == 0");
            NotificationListener orderListener = new AcceptReport();
            orderSubscription.addListener(orderListener);
        } catch (Exception e) {
            log.info(e);
        }
    }

    public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
        SimSendOrder my = new SimSendOrder();
        /*
         Session session = NewHibernateUtil.getOpenSession();
         Transaction t = session.beginTransaction();
         order1.setDateTime(Date.valueOf(LocalDate.now()));
         order1.setSubmitTime(Time.valueOf(LocalTime.now()));
         order1.setTradeDate(Date.valueOf(LocalDate.now()));
         log.info(JSON.toJSON(order1));
         session.saveOrUpdate(order);
         session.saveOrUpdate(order1);
         log.info("事务提交开始");
         t.commit();
         log.info("事务提交完成");
         NewHibernateUtil.closeSession(session);
         */
        
        my.testsingleOrder();
    //    my.testBasketOrder();
    //    my.testCancelOrder();
    //    my.testBasketcancel();

    }
    private void testsingleOrder(){
        NewOrder order1= generOrder("600000","S","B", (float) 14.9,200,"2");
        NewOrder order2= generOrder("600000","S","S", (float) 14.9,200,"3");
        NewOrder order3= generOrder("000001","A","B", (float) 14.9,300,"4");
        NewOrder order4= generOrder("000001","A","S", (float) 14.9,300,"5");
        NewOrder order7= generOrder("000001","A","B", (float) 15.9,3000,"6");
        NewOrder order8= generOrder("000001","A","S", (float) 14.4,3000,"7");
        NewOrder order13= generOrder("000001","A","S", (float) 14.4,3000,"8");
        NewOrder order5= generOrder("600000","S","B", (float) 15.9,2000,"3");
        NewOrder order6= generOrder("600000","S","S", (float) 14.4,2000,"2");

        
        NewOrder order9= generOrder("00001","H","B", (float) 14.9,500,"3");
        NewOrder order10= generOrder("00001","H","S", (float) 14.9,200,"1");
        NewOrder order11= generOrder("00001","H","B", (float) 14.9,300,"0");
        NewOrder order12= generOrder("00001","H","S", (float) 14.9,300,"4");
        try {
            SendMsg(order1.EnCode(order1),1,0);
            SendMsg(order2.EnCode(order2),1,0);
            SendMsg(order3.EnCode(order3),1,0);
            SendMsg(order4.EnCode(order4),1,0);
            SendMsg(order5.EnCode(order5),1,0);
            SendMsg(order6.EnCode(order6),1,0);
            SendMsg(order7.EnCode(order7),1,0);
            SendMsg(order8.EnCode(order8),1,0);
            SendMsg(order5.EnCode(order9),1,0);
            SendMsg(order6.EnCode(order10),1,0);
            SendMsg(order7.EnCode(order11),1,0);
            SendMsg(order8.EnCode(order12),1,0);
            SendMsg(order8.EnCode(order13),1,0);

        } catch (IOException ex) {
            log.error(ex);
        }
    }
    private void testBasketOrder(){
        NewOrder order1= generOrder("600000","S","B", (float) 14.9,200,"1");
        NewOrder order2= generOrder("600000","S","S", (float) 14.9,200,"1");
        NewOrder order3= generOrder("600000","S","B", (float) 14.9,300,"0");
        NewOrder order4= generOrder("600000","S","S", (float) 14.9,300,"0");
        NewOrder order5= generOrder("600000","S","B", (float) 14.9,2000,"1");
        NewOrder order6= generOrder("600000","S","S", (float) 14.9,2000,"1");
        NewOrder order7= generOrder("600000","S","B", (float) 14.9,3000,"0");
        NewOrder order8= generOrder("600000","S","S", (float) 14.9,3000,"0");
        BasketOrders orders = new BasketOrders();
        orders.AddOrder(order1);
        orders.AddOrder(order2);
        orders.AddOrder(order3);
        orders.AddOrder(order4);
        orders.AddOrder(order5);
        orders.AddOrder(order6);
        orders.AddOrder(order7);
        orders.AddOrder(order8);
        
        log.info(JSON.toJSON(orders));
        try {
            SendMsg(orders.EnCode(orders),2,0);
        } catch (IOException ex) {
            log.error(ex);
        }
    }
    private void testCancelOrder(){
        CancelOrder corder1 = gennerCancelOrder(1,0);
        CancelOrder corder2 = gennerCancelOrder(2,0);
        CancelOrder corder3 = gennerCancelOrder(3,0);
        CancelOrder corder4 = gennerCancelOrder(4,0);
        CancelOrder corder5 = gennerCancelOrder(5,0);
        CancelOrder corder6 = gennerCancelOrder(6,0);
        try {
            SendMsg(corder1.EnCode(corder1),4,0);
            SendMsg(corder1.EnCode(corder2),4,0);
            SendMsg(corder1.EnCode(corder3),4,0);
            SendMsg(corder1.EnCode(corder4),4,0);
            SendMsg(corder1.EnCode(corder5),4,0);
            SendMsg(corder1.EnCode(corder6),4,0);
 
        } catch (IOException ex) {
            log.error(ex);
        }
        
    }
    private void testBasketcancel(){
        CancelOrder corder1 = gennerCancelOrder(9,100);
        CancelOrder corder2 = gennerCancelOrder(10,100);
        CancelOrder corder3 = gennerCancelOrder(9,100);
        CancelOrder corder4 = gennerCancelOrder(10,100);
        CancelOrder corder5 = gennerCancelOrder(9,100);
        CancelOrder corder6 = gennerCancelOrder(10,100);
        BasketCancelOrders co = new BasketCancelOrders();
        co.AddCancelOrder(corder1);
        co.AddCancelOrder(corder2);
        co.AddCancelOrder(corder3);
        co.AddCancelOrder(corder4);
        co.AddCancelOrder(corder5);
        co.AddCancelOrder(corder6);
        co.setCancelBasketID(1);
        log.info("篮子撤单："+JSON.toJSON(co));
        try {
            SendMsg(co.EnCode(co),5,0);
 
        } catch (IOException ex) {
            log.error(ex);
        }
    }
    private CancelOrder gennerCancelOrder(int id,int qty){
        CancelOrder corder = new CancelOrder();
        corder.setOrderId(id);
        corder.setCancelQty(qty);
        corder.setDealerUserId("jili");
        InetAddress addr;
        try {
            addr = InetAddress.getLocalHost();
            corder.setIp4(Ip2Int(addr.getHostAddress()));
            corder.setMac(getLocalMac(addr));
        } catch (UnknownHostException | SocketException ex) {
            log.error(ex);
        }
        corder.setTradeDate(Date.valueOf(LocalDate.now()));
        return corder;
    }
    private NewOrder generOrder(String obj,String mk,String bs,float price,int qty,String type){
        NewOrder order =new NewOrder();
        order.setAccountCode("26513SDD");
        order.setAlterUserId("jili");
        order.setBs(bs);
        order.setClassCode("A1");
        order.setCloseType("1");
        order.setDateTime(Date.valueOf(LocalDate.now()));
        order.setDateTimeStr(LocalDateTime.now().toString());
        order.setDealerUserId("jili");
        order.setHedgeFlag("1");
        InetAddress addr;
        try {
            addr = InetAddress.getLocalHost();
            order.setIp4(Ip2Int(addr.getHostAddress()));
            order.setMac(getLocalMac(addr));
        } catch (UnknownHostException | SocketException ex) {
            log.error(ex);
        }
        order.setMarketCode(mk);
        order.setObj(obj);
        order.setOpenClose("O");
        order.setOrderId(id++);
        order.setOrderPrice(price);
        order.setOrderQty(qty);
        order.setPosId("");
        order.setPriceType(type);
        order.setSubmitTime(Time.valueOf(LocalTime.now()));
        order.setTradeDate(Date.valueOf(LocalDate.now()));
        return order;
    }
    private void SendMsg(byte[] dd,int orderType,int pipID){
        //发送委托
        Notification order0 = new Notification();
        order0.set("Title", "Trade");
        order0.set("PipID", pipID);
        order0.set("OrderType", orderType);
        order0.set("Data", dd);
        SimSendOrder my = new SimSendOrder();
        //发送结束
        try {
            order0.set("Data", dd);
            elvin.send(order0);
        } catch (IOException ex) {
            log.error(ex);
        }
    }

    private static String getLocalMac(InetAddress ia) throws SocketException {
        // TODO Auto-generated method stub
        //获取网卡，获取地址
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        //   System.out.println("mac数组长度：" + mac.length);
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            //字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            //    System.out.println("每8位:" + str);
            if (str.length() == 1) {
                sb.append("0" + str);
            } else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }

    public static int Ip2Int(String strIp) {
        String[] ss = strIp.split("\\.");
        if (ss.length != 4) {
            return 0;
        }
        byte[] bytes = new byte[ss.length];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(ss[i]);
        }
        return byte2Int(bytes);
    }

    public static String int2Ip(int intIp) {
        byte[] bytes = int2byte(intIp);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(bytes[i] & 0xFF);
            if (i < 3) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    private static byte[] int2byte(int i) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (0xff & i);
        bytes[1] = (byte) ((0xff00 & i) >> 8);
        bytes[2] = (byte) ((0xff0000 & i) >> 16);
        bytes[3] = (byte) ((0xff000000 & i) >> 24);
        return bytes;
    }

    private static int byte2Int(byte[] bytes) {
        int n = bytes[0] & 0xFF;
        n |= ((bytes[1] << 8) & 0xFF00);
        n |= ((bytes[2] << 16) & 0xFF0000);
        n |= ((bytes[3] << 24) & 0xFF000000);
        return n;
    }
}
